//
//  SilentTimeListViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/22.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SilentTimeListViewController.h"
#import "SetSilentTimeViewController.h"
#import "AppDelegate.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
@interface SilentTimeListViewController ()

@property (nonatomic,strong) SyncManager *syncManager;
@property (nonatomic,strong) DataManager *dataManager;
@property (nonatomic,weak) AppDelegate *mydelegate;

@end

@implementation SilentTimeListViewController
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize silentTableViewCell;
@synthesize addSafeAreaTableViewCell;
@synthesize tableView;
@synthesize tableViewHeight;
@synthesize mydelegate;
-(void)dealloc
{
    [mydelegate.silentDetailsDataArray removeAllObjects];
    mydelegate.silentDetailsDataArray=NULL;
    mydelegate=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"免打扰时段";
    mydelegate=[[UIApplication sharedApplication] delegate];
    mydelegate.silentDetailsDataArray=[[NSMutableArray alloc] init];
    if(mydelegate.isAdmin==YES)
    {
        self.navigationItem.rightBarButtonItem=self.navRightButton;
        [self initNavButton];
        self.navigationItem.rightBarButtonItem=nil;
    }
    [self initDataProxy];
    [self worktable];
    
    
    // Do any additional setup after loading the view from its nib.
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
-(void)getAllSilentData{
    [mydelegate.silentDetailsDataArray removeAllObjects];
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    NSArray *silentArray=[self.dataManager getSilentList:watchId];
    for (int i=0;i<silentArray.count;i++)
    {
        Silent *silent=[silentArray objectAtIndex:i];
        NSString *period=[silent.startTime stringByAppendingString:@"-"];
        period=[period stringByAppendingString:silent.endTime];
        
        NSString *activeString;
        if (silent.active){activeString=@"1";}else{activeString=@"0";}
        
        NSDictionary *dicOne = [NSDictionary dictionaryWithObjectsAndKeys:period,@"time",[self changeSilentCycle:silent.cycle],@"rate",activeString,@"status",silent.slient_id,@"silentID",nil];
        [mydelegate.silentDetailsDataArray addObject:dicOne];
    }
}
-(NSString *)changeSilentCycle:(NSString *)cycle
{
    NSString *newCycle=@"";
    
    if ([cycle isEqualToString:@"1,2,3,4,5,6,7"]){return @"每天";}

    for (int i=0;i<cycle.length;i++)
    {
        if (i%2==0)
        {
            NSRange range = NSMakeRange(i, 1);
            NSString *subString = [cycle substringWithRange:range];
            if ([subString isEqual:@"1"]){newCycle=[newCycle stringByAppendingString:@"周一,"];}
            if ([subString isEqual:@"2"]){newCycle=[newCycle stringByAppendingString:@"周二,"];}
            if ([subString isEqual:@"3"]){newCycle=[newCycle stringByAppendingString:@"周三,"];}
            if ([subString isEqual:@"4"]){newCycle=[newCycle stringByAppendingString:@"周四,"];}
            if ([subString isEqual:@"5"]){newCycle=[newCycle stringByAppendingString:@"周五,"];}
            if ([subString isEqual:@"6"]){newCycle=[newCycle stringByAppendingString:@"周六,"];}
            if ([subString isEqual:@"7"]){newCycle=[newCycle stringByAppendingString:@"周日,"];}
        }
        
    }
    if ([newCycle isEqualToString:@""])
    {
        return newCycle;
    }
    else
    {
        NSRange range = NSMakeRange(0, newCycle.length-1);
        newCycle = [newCycle substringWithRange:range];
        return newCycle;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    
    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
    [self.view addSubview:loadingView];
    [loadingView startAnimating];
    [self getAllSilentData];
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    if(self.dataManager==NULL)
        return;
    Watch *selectWatch=[self.dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
        return;
    if(self.syncManager==NULL)
        return;
    [self.syncManager getSilent:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            [self getAllSilentData];
            [tableView reloadData];
            [loadingView stopAnimating];
        }
        else
        {
            [loadingView stopAnimating];
            [Tooler showHttpToast:result description:description msg:@"免打扰时段数据获取失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        }
    }];

}

-(void)worktable{
    [tableView setAllowsSelectionDuringEditing:YES];
    self.automaticallyAdjustsScrollViewInsets=NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate=self;
    tableView.dataSource=self;
    
    UINib *cellSilent = [UINib nibWithNibName:@"SilentTableViewCell" bundle:nil];
    [tableView registerNib:cellSilent forCellReuseIdentifier:@"silenttablecell"];
    self.silentTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"silenttablecell"];
    
    UINib *cellAdd = [UINib nibWithNibName:@"AddSafeAreaTableViewCell" bundle:nil];
    [tableView registerNib:cellAdd forCellReuseIdentifier:@"addSafeAreaCell"];
    self.addSafeAreaTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
    
}

- (void)initNavButton {
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(deleteAction)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteAction{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    if (self.tableView.editing)
    {
        [self.navRightButton setTitle:@"删除"];
    }
    else
    {
        [self.navRightButton setTitle:@"编辑"];
    }
}
-(void)switchAction:(UISwitch*)sender
{
    int x=sender.tag-100;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSMutableDictionary *dicOne=[myDelegate.silentDetailsDataArray objectAtIndex:x];
    NSString *silentID=[dicOne valueForKey:@"silentID"];
    Silent  *silent=[self.dataManager getSilent:silentID];
    if (silent.active)
    {
        silent.active=NO;
    }
    else
    {
        silent.active=YES;
    }
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    [self.syncManager setSilentPeriod:watchId silent:silent completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            
        if (result==SUCESS)
        {
            //[self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            NSLog(@"%@",description);
        }
        
    }];
        
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CGRect rect = [UIScreen mainScreen].bounds;
    if(mydelegate.isAdmin==NO)
    {
        if (80 * mydelegate.silentDetailsDataArray.count < rect.size.height) {
            tableViewHeight.constant = 80 * mydelegate.silentDetailsDataArray.count;
        }
        else
            tableViewHeight.constant = rect.size.height - 80;
        return mydelegate.silentDetailsDataArray.count;
    }
    else
    {
        if (80 * (mydelegate.silentDetailsDataArray.count+1) < rect.size.height) {
            tableViewHeight.constant = 80 * (mydelegate.silentDetailsDataArray.count+1);
        }
        else
            tableViewHeight.constant = rect.size.height - 80;
        
        
        
        return mydelegate.silentDetailsDataArray.count+1;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(indexPath.row == myDelegate.silentDetailsDataArray.count){
        AddSafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
        cell.navController=self.navigationController;
        cell=[self addCellLine:cell forIndex:indexPath.row];
        if (self.mydelegate.silentDetailsDataArray.count>=3)
        {
            cell.hidden=YES;
        }
        return cell;
    }
    SilentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"silenttablecell"];
    cell.navController=self.navigationController;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell = [cell getandSetData:[myDelegate.silentDetailsDataArray objectAtIndex:indexPath.row]];
    //Switch事件
    UISwitch *switchButton=[[UISwitch alloc]init];
    switchButton=(UISwitch *)cell.silentTimeOnOff;
    switchButton.tag=100+[indexPath row];
    if(mydelegate.isAdmin==NO)
    {
        cell.silentTimeOnOff.enabled=NO;
    }
    else
    {
        [cell.silentTimeOnOff addTarget:self action:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];
    }
    cell=[self addCellLine:cell forIndex:indexPath.row];
    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(myDelegate.isAdmin==NO){
        return UITableViewCellEditingStyleNone;
    }
    else{
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSArray *indexPaths = @[indexPath];
        //deleteRows++;
        //删除数据库里的数据
        User *user=[User sharedSingleton];
        NSString *userId=user.uid;
        Watch *watch=[self.dataManager getActiveWatch:userId];
        NSString *watchId=watch.deviceUid;
        NSMutableDictionary *dicOne=[mydelegate.silentDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *silentID=[dicOne valueForKey:@"silentID"];

        [self.syncManager deleteSilent:watchId silentId:silentID completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result==SUCESS){
                NSLog(@"成功！");
                [mydelegate.silentDetailsDataArray removeObjectAtIndex:[indexPath row]];  //删除数组里的数据
                [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];  //删除对应数据的cell
                [tableView reloadData];
            }
            else{
                NSLog(@"失败原因%@",description);
                [Tooler showHttpMsg:result description:description msg:@"免打扰时段删除失败"];
            }

        }];
        
        
    }
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (indexPath.row==myDelegate.silentDetailsDataArray.count) {
        return NO;
    }
    else
        return YES;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if(mydelegate.isAdmin==NO)
        return;
    if(indexPath.row == mydelegate.silentDetailsDataArray.count){
        if (mydelegate.silentDetailsDataArray.count>=3)
        {
            [LeoMsg showMsg:@"最大免打扰时段只能有3个"];
            return;
        }
        SetSilentTimeViewController *setSilentTimeViewController = [[SetSilentTimeViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:setSilentTimeViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    else
    {

        NSMutableDictionary *dicOne=[mydelegate.silentDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *silentID=[dicOne valueForKey:@"silentID"];
        
        
        NSDictionary *subdic=[[NSDictionary alloc]init];
        subdic=[mydelegate.silentDetailsDataArray objectAtIndex:indexPath.row];
        NSString *time=[NSString stringWithFormat:@"%@",[subdic objectForKey:@"time"]];
        NSArray *array = [time componentsSeparatedByString:@"-"]; //从字符A中分隔成2个元素的数组
        
        
        SetSilentTimeViewController *setSilentTimeViewController = [[SetSilentTimeViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        setSilentTimeViewController.startDateString=array[0];
        setSilentTimeViewController.endDateString=array[1];
        setSilentTimeViewController.rateString=[NSString stringWithFormat:@"%@",[subdic objectForKey:@"rate"]];
        setSilentTimeViewController.silentIDString=silentID;
        [self.navigationController pushViewController:setSilentTimeViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

-(UITableViewCell *)addCellLine:(UITableViewCell *)cell forIndex:(int)index
{
    NSArray *dic=self.mydelegate.silentDetailsDataArray;
    UILabel *line;
    if ((index==dic.count)||(index>=2))
    {
        NSLog(@"有最后一条！");
        line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
    }
    else
    {
        AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        if((myDelegate.isAdmin==NO)&&(index==dic.count-1)){
            line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
        }
        else{
            line=[[UILabel alloc]initWithFrame:CGRectMake(20, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-20, 1)];
        }
    }
    line.backgroundColor=[UIColor colorWithRed:226/255.0 green:226/255.0 blue:228/255.0 alpha:1.0];
    
    [cell addSubview:line];
    
    return cell;
}



@end
